import cv2
import numpy as np
import math

# 定义一个寻找最远距离的函数画出该线并且求得距离（读入图像，阈值，模板图像，线的颜色）
def wheremax(image,threshold,template, color):  # 传入灰度图，模板和颜色
    global img
    im = img.copy()
    w, h = template.shape[::-1]
    Max = 0
    # 模板匹配
    res = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
    # 设置阈值找到符合要求棋子的坐标
    loc = np.where(res >= threshold)
    # 计算长度并画线
    for pt1 in zip(*loc[::-1]):
        for pt2 in zip(*loc[::-1]):
            # 计算长度的平方
            diff1 = pt2[0] - pt1[0]
            diff2 = pt2[1] - pt1[1]
            fdiff1 = math.pow(diff1, 2)
            fdiff2 = math.pow(diff2, 2)
            dis = int(math.sqrt(fdiff1 + fdiff2))  # 开根号求两圆心距离
            # 若新长度比最大值大，复原图像并重新画线
            if dis > Max:
                Max = dis
                #得到棋子的中心点计算距离
                a = (int(pt1[0] + w / 2), int(pt1[1] + h / 2))
                b = (int(pt2[0] + w / 2), int(pt2[1] + h / 2))
                im = img.copy()
                cv2.line(im, a, b, color, 2)

            # 若与最大值相等，则画线(最长线段不止一条)
            if dis == Max:
                a = (int(pt1[0] + w / 2), int(pt1[1] + h / 2))
                b = (int(pt2[0] + w / 2), int(pt2[1] + h / 2))
                cv2.line(im, a, b, color, 2)
    img = im.copy()
    #输出最大距离
    print(Max)

# 读取部分
image = cv2.imread('D:\\pyjpg\\checkerboard .png', 1)
img = image.copy()
img_grey = cv2.imread('D:\\pyjpg\\checkerboard .png',0)  # 读取灰度图，用于下面的霍夫检测
img1 = cv2.imread('D:\\pyjpg\\white.png', 0)
img2 = cv2.imread('D:\\pyjpg\\black.png', 0)

#找到最大距离并画线
print("白色最大距离为：")
wheremax(img_grey,0.6, img1, (0, 0, 255))
print("黑色最大距离为：")
wheremax(img_grey,0.75, img2, (0, 255, 0))

# 霍夫变换部分
edges = cv2.Canny(img_grey, 50, 150, apertureSize=3)#边缘检测
lines = cv2.HoughLines(edges,1,np.pi/180,114)
# for  rho,theta  in  lines[0]:  # 此语句只能显示一条直线
lines = cv2.HoughLines(edges, 1, np.pi / 180, 200)  # 霍夫变换检测直线
for line in lines:  # 找出直线位置并画线
    rho, theta = line[0]
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a * rho
    y0 = b * rho
    x1 = int(x0 + 1000 * (-b))
    y1 = int(y0 + 1000 * a)
    x2 = int(x0 - 1000 * (-b))
    y2 = int(y0 - 1000 * a)
    cv2.line(img, (x1, y1), (x2, y2), (255, 0, ), 2)#将获取的端点连线

#展示
cv2.imshow('okk', img)
cv2.waitKey(0)
